﻿using Identity.API.IdentityConfig;
using Identity.API.Models;
using Identity.API.Service;
using IdentityServer4.Configuration;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Identity.API.StartupConfigurationServices
{
    public static class IdentityServerService
    {
        public static void AddIdentityService(this IServiceCollection services, IConfiguration configuration, string migrationsAssembly)
        {
            var ConnectionString = configuration.GetConnectionString("MySqlDev");
            var usedDb = configuration.GetValue<bool>("IdentityServerIsUsedDb");
            if (usedDb)
            {
                services
                    .AddIdentityServer(options =>
                    {
                        options.IssuerUri = "null";
                        options.Authentication.CookieLifetime = TimeSpan.FromHours(2);

                        options.Events.RaiseErrorEvents = true;
                        options.Events.RaiseInformationEvents = true;
                        options.Events.RaiseFailureEvents = true;
                        options.Events.RaiseSuccessEvents = true;

                        options.UserInteraction = new UserInteractionOptions
                        {
                            LogoutUrl = "/Account/Logout",
                            LoginUrl = "/Account/Login",
                            LoginReturnUrlParameter = "returnUrl"
                        };
                    })
                    .AddIdentityServerSigningCredential(configuration)
                    .AddAspNetIdentity<ApplicationUser>()
                    .AddConfigurationStore(options =>
                    {
                        options.ConfigureDbContext = builder => builder.UseMySql(
                            ConnectionString,
                            new MySqlServerVersion(new Version(10, 1, 40)),
                            mysqlOptions =>
                            {
                                mysqlOptions.MigrationsAssembly(migrationsAssembly);
                                mysqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                            });
                    })
                    .AddOperationalStore(options =>
                    {
                        options.ConfigureDbContext = builder => builder.UseMySql(
                            ConnectionString,
                            new MySqlServerVersion(new Version(10, 1, 40)),
                            mysqlOptions =>
                            {
                                mysqlOptions.MigrationsAssembly(migrationsAssembly);
                                mysqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                            });
                    })
                    .Services.AddTransient<IProfileService, ProfileService>();
            }
            else
            {
                services
                    .AddIdentityServer(options =>
                    {
                        options.IssuerUri = null;
                        options.Authentication.CookieLifetime = TimeSpan.FromHours(2);

                        options.UserInteraction = new UserInteractionOptions
                        {
                            LogoutUrl = "/Account/Logout",
                            LoginUrl = "/Account/Login",
                            LoginReturnUrlParameter = "returnUrl"
                        };
                    })
                    .AddDeveloperSigningCredential(persistKey: false)
                    .AddAspNetIdentity<ApplicationUser>()
                    .AddInMemoryApiResources(Config.GetApiResources)
                    .AddInMemoryApiScopes(Config.GetApiScopes)
                    .AddInMemoryClients(Config.GetClients)
                    .AddInMemoryIdentityResources(Config.GetIdentityResources);                    
            }
        }
    }
}
